<template>
  <div>
    <template v-if="params.tableMain == 0">
      <el-row style="justify-content: space-between">
        <el-row>
          <p class="pinformation">方案列表</p>
          <p class="totalStyle">共 {{ projectList.length }} 条数据</p>
        </el-row>
      </el-row>
      <el-table ref="projectRef" :data="projectList" v-loading="projectLoading">
        <el-table-column show-overflow-tooltip label="方案编号" align="center" prop="projectCode" />
        <el-table-column label="检测时间" align="center">
          <template #default="scope">
            <el-date-picker v-model="scope.row.dateRange" value-format="YYYY-MM-DD" type="daterange" range-separator="-"
              start-placeholder="开始日期" end-placeholder="结束日期" @change="pickerChange(scope.row)"
              style="width: 100%"></el-date-picker>
          </template>
        </el-table-column>
      </el-table>
      <el-row style="margin-top: 5px">
        <p class="pinformation">附件列表</p>
        <p class="totalStyle">共 {{ annexList.length }} 条数据</p>
        <el-row style="padding-bottom: 5px; margin-left: 20px">
          <el-button type="success" link @click="handleAnnexAdd">新增</el-button>
        </el-row>
      </el-row>
      <el-table ref="projectRef" :data="annexList" v-loading="annexLoading">
        <el-table-column label="序号" type="index" width="70" align="center" />
        <el-table-column label="文件名称" align="center" show-overflow-tooltip>
          <template #default="scope">
            <span @click="downloadFile(scope.row)" class="fileNameHover">{{
      scope.row.fileName
    }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150">
          <template #default="scope">
            <el-button link type="success" icon="Edit" @click="editAnnex(scope.row)">编辑</el-button>
            <el-button link type="success" icon="Delete" @click="deleteAnnex(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </template>
    <template v-if="params.isChild == 1">
      <el-form-item label="前处理：" prop="sampleCode" label-width="100" style="margin-top: 10px">
        <el-select style="width: 100%" filterable placeholder="请选择前处理" v-model="pretreatmentForm.handleMc"
          @change="handleChange">
          <el-option v-for="item in pretreatmentList" :key="item" :label="item" :value="item" />
        </el-select>
      </el-form-item>
      <!-- <p class="pinformation">搜索</p>
      <el-form :modal="queryForm" ref="queryRef" label-width="100">
        <el-row>
          <el-col :span="8">
            <el-form-item label="样品编号：" prop="sampleCode">
              <el-input v-model="queryForm.sampleCode" placeholder=""></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="检测项目：" prop="jcxmName">
              <el-input v-model="queryForm.jcxmName" placeholder=""></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-row style="justify-content: center">
              <el-button type="success">搜索</el-button>
              <el-button class="business resetBtn">重置</el-button>
            </el-row>
          </el-col>
        </el-row>
      </el-form>
      <p class="pinformation">统计</p>
      <el-row>
        <el-form-item label="样品编号数：" prop="sampleCount" label-width="100">
          {{ statisticForm.sampleCount }}
        </el-form-item>
        <el-form-item label="检测项目数：" prop="jcxmCount" label-width="100">
          {{ 1 }}
        </el-form-item>
        <el-form-item label="原样编号数：" prop="typeCount" label-width="100">
          {{ 1 }}
        </el-form-item>
      </el-row> -->
    </template>
    <p class="pinformation">操作</p>
    <el-row style="padding-left: 10px">
      <el-button type="success" @click="handlePaste">复制上次</el-button>
      <el-button style="background-color: #e6a23c; color: #fff" @click="handleDataRel">数据引用</el-button>
      <el-button style="background-color: #6200ff; color: #fff" @click="handleImport">仪器数据导入</el-button>
      <el-button style="background-color: #6200ff; color: #fff" @click="handleUseRecord">仪器使用记录</el-button>
    </el-row>
    <el-row style="padding-left: 10px; margin-top: 10px">
      <el-button style="background-color: #6200ff; color: #fff" @click="handleEditLimit">修改检出限</el-button>
    </el-row>

    <el-dialog :class="'el-dialog-theme3'" append-to-body draggable :close-on-click-modal="false"
      v-model="annexOpen" :title="annexTitle" width="500px" @close="annexClose">
      <el-form :model="annexForm" ref="annexRef" label-width="80">
        <fileUpload v-model="annexForm.fileList" :autoUpload="true" :fileId="annexForm.fileId"
          :fileType="['jpg', 'gif', 'bmp', 'png', 'pdf']"></fileUpload>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="success" @click="annexSave">保存</el-button>
          <el-button type="danger" @click="annexOpen = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 仪器数据导入对话框 -->
    <el-dialog :class="'el-dialog-theme3'" :title="instrument.title" v-model="instrument.open"
      width="400px" append-to-body draggable :close-on-click-modal="false">
      <el-upload ref="uploadRef" :limit="1" accept=".pdf" :action="instrument.url" :headers="instrument.headers"
        :on-change="handleOnChange" :disabled="instrument.isUploading" :on-progress="handleFileUploadProgress"
        :on-error="handleUploadError" :on-success="handleFileSuccess" :auto-upload="false" drag>
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <span>仅允许导入pdf格式文件。</span>
          </div>
        </template>
      </el-upload>
      <el-form-item label="仪器包：" style="margin-top: 20px">
        <el-select v-model="packageId" placeholder="请选择仪器包" clearable filterable style="width: 100%"
          @change="packageChange">
          <el-option v-for="item in packageList" :label="item.packageName" :value="item.packageId"
            :key="item.packageId" />
        </el-select>
      </el-form-item>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="success" @click="submitFileForm">确 定</el-button>
          <el-button type="danger" @click="handleCancal">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog :class="'el-dialog-theme3'" title="修改检出限" v-model="LimitOpen" width="700px"
      append-to-body draggable :close-on-click-modal="false" @close="limitClose">
      <el-table :data="LimitTable" v-loading="limitLoad" max-height="50vh">
        <el-table-column label="序号" type="index" width="70" align="center" />
        <el-table-column show-overflow-tooltip label="检测类别" align="center" prop="jclbName" />
        <el-table-column show-overflow-tooltip label="检测项目" align="center" prop="jcxmName" />
        <el-table-column label="检出限" align="center">
          <template #default="scope">
            <el-input v-model="scope.row.checkLimitValue" clearable maxlength="8"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="单位" align="center" prop="checkLimitUnit">
          <template #default="scope">
            <el-select v-model="scope.row.checkLimitUnit" placeholder="" clearable filterable>
              <el-option v-for="item in unitList" :key="item.unitName" :value="item.unitName" :label="item.unitName">
                <span v-html="proxy.getSupAndSub(item.unitName)"></span>
              </el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column show-overflow-tooltip label="机构检出限" align="center">
          <template #default="scope">
            {{ scope.row.orgCheckLimit }}{{ scope.row.orgCheckLimitUnit }}
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="success" @click="checkLimitValueSave">保 存</el-button>
          <el-button type="danger" @click="checkLimitValueCancal">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
    <instrumentDia :lMId="props.lMId" :useTypeId="useTypeId" ref="instrumentRef" @save="save" />
  </div>
</template>

<script setup>
import instrumentDia from "@/components/instrument/index";

import { getToken } from "@/utils/auth";
import {
  getProjectList,
  labTask,
  listHandle,
  listAnnex,
  delAnnex,
  formAnnex,
  saveAnnex,
  queryDataRel,
  getPackageList,
  pasteData,
  handleSave,
  listChecklimit,
  getLimtList,
  editLimitSave,
} from "@/api/lab/labMethod";
import bus from "@/utils/eventBus";
import { getUnitList } from "@/api/store/unit";

const { proxy } = getCurrentInstance();

const projectList = ref([]);
const projectLoading = ref(false);
const annexList = ref([]);
const queryForm = ref({});
const statisticForm = ref({ sampleCount: 0 });
const pretreatmentList = ref([]);
const pretreatmentForm = ref({});
const instrumentRef = ref(null);
const useTypeId = ref(1);
const packageId = ref("");
const packageList = ref([]);
const unitList = ref([]);
const LimitTable = ref([]);
const LimitOpen = ref(false);

const myId = ref("");
const params = ref({ isChild: 0 });
const props = defineProps({
  params: {
    type: Object,
    required: true,
  },
  lMId: {
    type: String,
  },
  methodId: {
    type: String,
  },
  projectId: {
    type: String,
  },
});
/*** 仪器导入数据 */
const instrument = reactive({
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: "",
  // 是否禁用上传
  isUploading: false,
  // 设置上传的请求头部
  headers: { Authorization: "Bearer " + getToken() },
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + "/lims/labMethod/importData/",
});
/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
  instrument.isUploading = true;
};
/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
  packageId.value = "";
  instrument.open = false;
  isProgress.value = false;
  instrument.isUploading = false;
  proxy.$refs["uploadRef"].handleRemove(file);
  proxy.$modal.msgSuccess("仪器导入成功！");
  bus.emit("showInstrumentData", response.data);
};

const isProgress = ref(false);

function handleOnChange(obj, list) {
  if (list.length == 0) {
    isProgress.value = false;
  } else {
    isProgress.value = true;
  }
}

/** 提交上传文件 */
function submitFileForm() {
  if (!packageId.value) {
    proxy.$modal.msgError("仪器包不能为空！");
    return;
  }
  if (!isProgress.value) {
    proxy.$modal.msgError("文件不能为空！");
    return;
  }
  proxy.$refs["uploadRef"].submit();
}

function handleCancal() {
  instrument.open = false;
  packageId.value = "";
  isProgress.value = false;
}

/** 导入按钮操作 */
function handleImport() {
  bus.emit("submit" + params.value.tFId, {
    isAutoSave: true,
    isShowTable: true,
    isReport: true,
  });
}

bus.off("yqdr");
bus.on("yqdr", () => {
  instrument.title = "仪器数据导入";
  instrument.open = true;
  getPackageList(props.params.tFId).then((res) => {
    packageList.value = res.data;
  });
});

function listProject() {
  let params = {};
  if (props.projectId) {
    params.lMId = props.lMId;
  } else {
    params.pId = props.lMId;
  }
  getProjectList(params).then((res) => {
    projectList.value = res.data;
    projectList.value.forEach((item) => {
      item.dateRange = [];
      item.dateRange[0] = item.startDate;
      item.dateRange[1] = item.endDate;
    });
  });
}
function handleChange() {
  listChecklimit({ handleMc: pretreatmentForm.value.handleMc, lMId: props.lMId }).then(
    (res) => {
      if (res.code != 200) return;
      let data = { handleMc: pretreatmentForm.value.handleMc };
      if (pretreatmentForm.value.handleMc) {
        data.handleMc = pretreatmentForm.value.handleMc;
      }
      if (res.data) {
        data.sampleCheckLimitList = res.data[0];
        data.distinctCheckLimitListByJcxm = res.data[1];
      }
      bus.emit("setHandle", data);
    }
  );
  // bus.emit("setHandle", pretreatmentForm.value.handleMc);
}
//读取样品检出限
bus.off("handleByTable");
bus.on("handleByTable", () => {
  listHandle(props.lMId).then((res) => {
    pretreatmentList.value = res.data.handleMcList;
    pretreatmentForm.value.handleMc = res.data.handleMc;
    let data = {};
    if (pretreatmentForm.value.handleMc) {
      data.handleMc = pretreatmentForm.value.handleMc;
    }
    if (res.data.sampleCheckLimitList) {
      data.sampleCheckLimitList = res.data.sampleCheckLimitList;
      data.distinctCheckLimitListByJcxm = res.data.distinctCheckLimitListByJcxm;
    }
    bus.emit("setHandle", data);
  });
  // handleMcView({ lMId: props.lMId }).then(res => {
  //   pretreatmentForm.value.handleMc = res.data
  // })
});
function selectHandle() { }
nextTick(() => {
  params.value = props.params;
  myId.value = params.value.myId;
  annexLoading.value = true;
  if (params.value.tableMain == 0) {
    listProject();
    listAnnex({ groupId: props.lMId, typeId: 27 }).then((res) => {
      annexLoading.value = false;
      annexList.value = res.data;
    });
  }
});

const emits = defineEmits(["changeDate"], ["search"]);

function pickerChange(row) {
  row.startDate = row.dateRange[0];
  row.endDate = row.dateRange[1];
  labTask(row).then((res) => {
    if (props.projectId) {
      emits("changeDate");
    }
  });
}

// -------------------------------附件-----------------------------
const annexOpen = ref(false);
const annexLoading = ref(false);
const annexTitle = ref("");
const annexForm = ref({ fileList: [] });

function annexClose() {
  annexForm.value = { fileList: [] };
}

function annexSave() {
  if (!annexForm.value.fileId) {
    annexForm.value.fileId = annexForm.value.fileList[0].fileId;
  }
  annexForm.value.groupId = props.lMId;
  annexForm.value.typeId = 27;
  annexForm.value.fileName = annexForm.value.fileList[0].fileName;
  annexForm.value.fileSizeDisplay = annexForm.value.fileList[0].fileSizeDisplay;
  delete annexForm.value.fileList;
  saveAnnex(annexForm.value).then((res) => {
    annexOpen.value = false;
    annexTitle.value = "";
    proxy.$modal.msgSuccess("保存成功");
    annexLoading.value = true;
    listAnnex({ groupId: props.lMId, typeId: 27 }).then((res) => {
      annexLoading.value = false;
      annexList.value = res.data;
    });
  });
}

function handleAnnexAdd() {
  annexOpen.value = true;
  annexTitle.value = "新增附件";
  nextTick(() => {
    proxy.$refs["annexRef"].clearValidate();
  });
}

function deleteAnnex(row) {
  proxy.$modal.confirm("确定要删除吗？").then(() => {
    delAnnex(row.fileId).then((res) => {
      annexLoading.value = true;
      listAnnex({ groupId: props.lMId, typeId: 27 }).then((res) => {
        annexLoading.value = false;
        annexList.value = res.data;
      });
    });
  });
}

function editAnnex(row) {
  formAnnex(row.fileId).then((res) => {
    annexTitle.value = "编辑附件";
    annexOpen.value = true;
    annexForm.value = {
      fileList: [
        {
          fileName: res.data.fileName,
          fileId: res.data.fileId,
          fileSizeDisplay: res.data.fileSizeDisplay,
        },
      ],
      groupId: res.data.groupId,
      fileId: res.data.fileId,
      typeId: res.data.typeId,
    };
    nextTick(() => {
      proxy.$refs["annexRef"].clearValidate();
    });
  });
}

// 上传失败
function handleUploadError(err) {
  instrument.isUploading = false;
  proxy.$modal.msgError("导入数据失败，原因：" + err.message);
}

/**
 * 数据引用
 */
function handleDataRel() {
  proxy.$modal.loading("正在引用数据，请稍候...");
  queryDataRel(props.params.tFId)
    .then((res) => {
      proxy.$modal.closeLoading();
      if (!res.data) {
        proxy.$modal.msgError("未查询到需要引用的数据！");
        return;
      }
      bus.emit("setRelData", res.data);
    })
    .catch(() => {
      proxy.$modal.closeLoading();
    });
}

function downloadFile(row) {
  proxy.$modal.loading("正在下载文件，请稍候...");
  proxy.$download.localFile(row.fileId, row.fileName).then((res) => {
    proxy.$modal.closeLoading();
  });
}

function handleUseRecord() {
  instrumentRef.value.handleUseRecord();
}

const limitLoad = ref(false);

function handleEditLimit() {
  if (!pretreatmentForm.value.handleMc) {
    proxy.$modal.msgError("请选择前处理");
    return;
  }

  let data = {
    method: beforEditLimit,
  };
  bus.emit("saveCallback", data);
}

function beforEditLimit() {
  LimitOpen.value = true;
  limitLoad.value = true;
  getUnitList().then((res) => {
    unitList.value = res.data;
  });
  getLimtList(props.lMId).then((res) => {
    LimitTable.value = res.data;
    limitLoad.value = false;
  });
}

function handlePaste() {
  pasteData(props.lMId).then((res) => {
    bus.emit("copyLast", res.data);
  });
}

function save(sourceFlag) {
  if (sourceFlag && typeof sourceFlag == 'string') {
    bus.emit("submit" + params.value.tFId, { isAutoSave: sourceFlag });
  } else {
    bus.emit("submit" + params.value.tFId, { isAutoSave: true, isShowTable: true });
  }
}

function packageChange() {
  instrument.url =
    import.meta.env.VITE_APP_BASE_API +
    "/lims/labMethod/importData/" +
    props.params.tFId +
    "/" +
    packageId.value;
}

function checkLimitValueSave() {
  for (const item of LimitTable.value) {
    if (!/^\d+(\.\d+)?$/.test(item.checkLimitValue)) {
      proxy.$modal.msgError("请输入正确的数字");
      return;
    }
  }
  editLimitSave({
    lMId: props.lMId,
    distinctCheckLimitListByJcxm: LimitTable.value,
  }).then((res) => {
    LimitOpen.value = false;
    proxy.$modal.msgSuccess("操作成功");
    emits("search");
  });
}

function checkLimitValueCancal() {
  LimitOpen.value = false;
}

function limitClose() {
  LimitTable.value = [];
}
</script>
